package cn.us.eagle.generic.dao.hibernate;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import cn.us.eagle.generic.dao.GenericDao;

import java.io.Serializable;
import java.util.List;

/**
 * 共用式泛型DAO实现类（基于hibernate4）
 * 
 * @author ReasonZhong
 * 
 * @param <T>
 *            泛型类
 * @param <PK>
 *            泛型类主键
 */
@Repository("genericDao")
public class GenericDaoImpl<T, PK extends Serializable> implements
		GenericDao<T, PK> {

	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public T save(T model) {
		getSession().save(model);
		return model;
	}

	public void saveOrUpdate(T model) {
		getSession().saveOrUpdate(model);

	}

	public void update(T model) {
		getSession().update(model);
	}

	public void merge(T model) {
		getSession().merge(model);
	}

	public void delete(Class<T> entityClass, PK id) {
		getSession().delete(get(entityClass, id));
	}

	public void deleteObject(T model) {
		getSession().delete(model);
	}

	@SuppressWarnings("unchecked")
	public T get(Class<T> entityClass, PK id) {
		return (T) getSession().get(entityClass, id);

	}

	public int countAll(Class<T> entityClass) {
		Criteria criteria = getSession().createCriteria(entityClass);
		criteria.setProjection(Projections.rowCount());
		return ((Long) criteria.uniqueResult()).intValue();
	}

	@SuppressWarnings("unchecked")
	public List<T> listAll(Class<T> entityClass) {
		Criteria criteria = getSession().createCriteria(entityClass);
		return criteria.list();
	}

}
